import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class Limited extends StatefulWidget {
  final int lockId;
  const Limited({super.key, required this.lockId});

  @override
  State<StatefulWidget> createState() => _LimitedState();

}

class _LimitedState extends State<Limited> {
  final FocusNode _receiverFocus = FocusNode();
  final FocusNode _nameFocus = FocusNode();
  final DateTime currentDate = DateTime.now();
  final Map<String, dynamic> _params = {
    "account": null,
    "name": "",
    "startDate": DateTime.now(),
    "endDate": DateTime.now(),
    "remote": false,
    "icCard": false,
    "fingerprint": false,
  };

  bool _canSend() {
    bool timePass = false;
    print("开始时间：${_params["startDate"] is DateTime}");
    var startDate = _params["startDate"] is DateTime ? _params["startDate"].millisecondsSinceEpoch : DateTime.parse(_params["endDate"]).millisecondsSinceEpoch;
    var endDate = _params["startDate"] is DateTime ? _params["endDate"].millisecondsSinceEpoch : DateTime.parse(_params["endDate"]).millisecondsSinceEpoch;

    if (startDate != endDate && endDate > startDate) {
      timePass = true;
    }
    return Utils.isNotEmpty(_params["account"]) && Utils.isNotEmpty(_params["name"]) && timePass;
  }

  void _sendKey() async {
      Map<String, dynamic> data = {
        ..._params,
        "lockId": widget.lockId,
        "startDate": DateTools.formatTime(_params["startDate"].millisecondsSinceEpoch),
        "endDate": DateTools.formatTime(_params["endDate"].millisecondsSinceEpoch),
      };
      EasyLoading.show();
      await lockApi.sendKey(data);
      EasyLoading.dismiss();
      EasyLoading.showToast("钥匙发送成功");
      Stacker.pop(true);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(ThemeVars.paddingPage),
      children: [
        MenuBlock(
          items: [
            MenuBlockItem(
              text: "接受者账号",
              showArrow: false,
              suffix: TextField(
                focusNode: _receiverFocus,
                textAlign: TextAlign.right,
                decoration: const InputDecoration(
                  hintText: "手机号",
                ),
                onChanged: (value) => setState(() {
                  _params["account"] = value;
                }),
                onTapOutside: (event){
                  _receiverFocus.unfocus();
                },
              )
            ),
            MenuBlockItem(
              text: "姓名",
              showArrow: false,
              suffix: TextField(
                focusNode: _nameFocus,
                textAlign: TextAlign.right,
                decoration: const InputDecoration(
                  hintText: "请输入",
                ),
                onChanged: (value) => setState(() {
                  _params["name"] = value;
                }),
                onTapOutside: (event){
                  _nameFocus.unfocus();
                },
              )
            ),
          ]
        ),
        const SizedBox(height: 12,),
        MenuBlock(
          items: [
            MenuBlockItem(
              text: "生效时间",
              showArrow: true,
              suffix: Text(
                DateTools.formatTime(_params["startDate"].millisecondsSinceEpoch, format: "{y}-{m}-{d} {h}:{i}"),
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: () {
                showDatetimePicker(
                  context: context,
                  initialDateTime: _params["startDate"],
                  minimumDate: currentDate,
                  onchange: (value) => setState(() {
                    print(value);
                    if (value != null) _params["startDate"] = value;
                  }),
                );
              },
            ),
            MenuBlockItem(
              text: "失效时间",
              showArrow: true,
              suffix: Text(
                DateTools.formatTime(_params["endDate"].millisecondsSinceEpoch,
                    format: "{y}-{m}-{d} {h}:{i}"),
                style: const TextStyle(color: ThemeVars.colorTextTer),
              ),
              onTap: () {
                showDatetimePicker(
                  context: context,
                  initialDateTime: _params["endDate"],
                  minimumDate: currentDate,
                  onchange: (value) => setState(() {
                    if (value != null) _params["endDate"] = value;
                  }),
                );
              },
            ),
          ]
        ),
        const SizedBox(height: 12,),
        MenuBlock(
          items: [
            MenuBlockItem(
              text: "远程开锁",
              showArrow: false,
              suffix: CupertinoSwitch(
                value: _params["remote"],
                activeColor: ThemeVars.colorPrimary,
                onChanged: (bool value) {
                  setState(() {
                    _params["remote"] = value;
                  });
                },
              ),
            ),
          ]
        ),
        const SizedBox(height: 12,),
        MenuBlock(
          items: [
            MenuBlockItem(
              text: "授予添加IC卡",
              showArrow: false,
              suffix: CupertinoSwitch(
                value: _params["icCard"],
                activeColor: ThemeVars.colorPrimary,
                onChanged: (bool value) {
                  setState(() {
                    _params["icCard"] = value;
                  });
                },
              ),
            ),
            MenuBlockItem(
              text: "授予添加指纹",
              showArrow: false,
              suffix: CupertinoSwitch(
                value: _params["fingerprint"],
                activeColor: ThemeVars.colorPrimary,
                onChanged: (bool value) {
                  setState(() {
                    _params["fingerprint"] = value;
                  });
                },
              ),
            ),
          ]
        ),
        Padding(
          padding: const EdgeInsets.only(top: 60,),
          child: Button(
            type: ButtonType.primary,
            onPressed: _canSend() ? () {
              print("下一步");
              _sendKey();
            } : null,
            child: const Text("发送"),
          ),
        )
      ],
    );
  }

}